<?php

namespace app\admin\controller\recovery;

use app\admin\model\RecoveryCategory;
use app\admin\model\RecoveryOrderStatus;
use app\common\controller\Backend;
use Exception;
use think\Cache;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use function explode;
use function json;
use function json_encode;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * RecoveryOrder模型对象
     * @var \app\admin\model\RecoveryOrder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\RecoveryOrder;
        $this->view->assign("typedataList", $this->model->getTypedataList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("storagedataList", $this->model->getStoragedataList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','rider'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as &$row) {
               // $row->ordertime += 3600;
//                /*计算预计回收价格*/
//                $goodsinfos = unserialize($row['goodsinfo']);
//                $estimate_price = 0;
//                foreach ($goodsinfos as $goodsinfo) {
//                    $data = RecoveryCategory::get($goodsinfo['recovery_category_id']);
//                    $estimate_price += $data->price*$goodsinfo['weight'];
//                }
//                $row['estimate_price'] = sprintf("%.2f", $estimate_price);
//                /*计算实际回收的价格*/
//                if($row['real_goods_info']){
//                    $realgoodsinfos = unserialize($row['real_goods_info']);
//                    $realestimate_price = 0;
//                    foreach ($realgoodsinfos as $realgoodsinfo) {
//                        $data = RecoveryCategory::get($realgoodsinfo['recovery_category_id']);
//                        $realestimate_price += $data->price*$realgoodsinfo['weight'];
//                    }
//                    $row['estimate_price'] = sprintf("%.2f", $realestimate_price);
//                }
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看订单详情
     */
    public function view($ids = null)
    {
        $this->relationSearch = true;
        $row = $this->model->with(['user','rider'])->find($ids)->toArray();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row['images'] = $row['images']==''?[]:explode(',', $row['images'] );

        /*计算预计回收价格*/
        $goodsinfos = unserialize($row['goodsinfo']);
        $estimate_price = 0;
        $estimate_price_end = 0;
        $estimate_weight = 0;
        $estimate_weight_end = 0;

        $estimate_price1 = 0;
        $estimate_price_end1 = 0;
        $estimate_weight1 = 0;
        $estimate_weight_end1 = 0;
        $goodsList = [];
        foreach ($goodsinfos as $goodsinfo) {
            $data = RecoveryCategory::with(['parent'])->find(['fa_recovery_category.id'=>$goodsinfo['recovery_category_id']]);
            if( $data ) $data->toArray();
            if($data['parent']['name']){
                $data['name'] = $data['parent']['name'].','.$data['name'];
            }
            if (strpos($goodsinfo['weight'], '-') !== false){
                $wei = explode('-',$goodsinfo['weight']);
                $estimate_price += $data['price'] * $wei[0];
                // $estimate_price += $price * $goodsinfo['weight'];
                $estimate_price_end += $data['price'] * $wei[1];
                $estimate_weight += $wei[0];
                $estimate_weight_end += $wei[1];

                $estimate_price1 = $data['price'] * $wei[0];
                // $estimate_price += $price * $goodsinfo['weight'];
                $estimate_price_end1 = $data['price'] * $wei[1];
                $estimate_weight1 = $wei[0];
                $estimate_weight_end1 = $wei[1];
            }else{
                $estimate_price += $data['price'] * $goodsinfo['weight'];
                $estimate_price_end += $data['price'] * $goodsinfo['weight'];
                $estimate_weight += $goodsinfo['weight'];
                $estimate_weight_end += $goodsinfo['weight'];

                $estimate_price1 = $data['price'] * $goodsinfo['weight'];
                $estimate_price_end1 = $data['price'] * $goodsinfo['weight'];
                $estimate_weight1 = $goodsinfo['weight'];
                $estimate_weight_end1 = $goodsinfo['weight'];
            }
            if(sprintf("%.2f", $estimate_price1) == sprintf("%.2f", $estimate_price_end1)){
                $estimate_price_dev1 = sprintf("%.2f", $estimate_price1);
            }else{
                $estimate_price_dev1 = sprintf("%.2f", $estimate_price1).'-'.sprintf("%.2f", $estimate_price_end1);
            }
            if(sprintf("%.2f", $estimate_weight1) == sprintf("%.2f", $estimate_weight_end1)){
                $estimate_weight_dev1 = sprintf("%.2f", $estimate_weight1);
            }else{
                $estimate_weight_dev1 = sprintf("%.2f", $estimate_weight1).'-'.sprintf("%.2f", $estimate_weight_end1);
            }
            $goodsList[] = [
                "recovery_category_name" => $data['name'],
                "recovery_category_id" => $data['id'],
               // "weight" => sprintf("%.2f", $goodsinfo['weight']),
                "weight" => $estimate_weight_dev1,
                'price' =>  '￥'.$data['price'].'元/',
                'unit' =>  $data['unit'],
               // 'total_price' => sprintf("%.2f", $goodsinfo['weight']*$data['price'])
                'total_price' => $estimate_price_dev1

            ];
           // $estimate_price += $data['price']*$goodsinfo['weight'];
           // $estimate_weight += $goodsinfo['weight'];

        }
        if(sprintf("%.2f", $estimate_price) == sprintf("%.2f", $estimate_price_end)){
            $estimate_price_dev = sprintf("%.2f", $estimate_price);
        }else{
            $estimate_price_dev = sprintf("%.2f", $estimate_price).'-'.sprintf("%.2f", $estimate_price_end);
        }
        if(sprintf("%.2f", $estimate_weight) == sprintf("%.2f", $estimate_weight_end)){
            $estimate_weight_dev = sprintf("%.2f", $estimate_weight);
        }else{
            $estimate_weight_dev = sprintf("%.2f", $estimate_weight).'-'.sprintf("%.2f", $estimate_weight_end);
        }
        ////$row['estimate_price'] = sprintf("%.2f", $estimate_price);
        $row['estimate_price'] = $estimate_price_dev;
        $row['estimate_weight'] = $estimate_weight_dev;
        ////$row['estimate_weight'] = sprintf("%.2f", $estimate_weight);
        $goodsList[] = [
            "recovery_category_name" => '',
            "recovery_category_id" => $data['id'],
            "weight" => $row['estimate_weight'],
            'price' =>  '客户合计',
            'unit' =>  '',
            'total_price' => $row['estimate_price']
        ];

        $row['goodsList'] = $goodsList;

        /*计算实际回收的价格*/
        if($row['real_goods_info']){
            $row['estimate_price'] = 0;
            $row['goodsList'] = [];

            $realgoodsinfos = unserialize($row['real_goods_info']);
            $realestimate_price = 0;
            $realestimate_weight = 0;
            $realgoodsList = [];
//            print_r($realgoodsinfos);die;
            foreach ($realgoodsinfos as $realgoodsinfo) {
//                $data = RecoveryCategory::with(['parent'])->find(['fa_recovery_category.id'=>$realgoodsinfo['recovery_category_id']]);
//                if( $data ) $data->toArray();
//                if($data['parent']['name']){
//                    $data['name'] = $data['parent']['name'].','.$data['name'];
//                }
                $realgoodsList[] = [
                    "recovery_category_name" => $realgoodsinfo['recovery_category_name'],
                    "recovery_category_id" => $realgoodsinfo['recovery_category_id'],
                    "weight" => sprintf("%.2f", $realgoodsinfo['weight']),
                    'price' => '￥'.$realgoodsinfo['price'].'元/' ,
                    'unit' =>  $realgoodsinfo['unit'],
                    'total_price' => sprintf("%.2f", $realgoodsinfo['weight']*$realgoodsinfo['price'])
                ];
                $realestimate_price += $realgoodsinfo['price']*$realgoodsinfo['weight'];
                $realestimate_weight += $realgoodsinfo['weight'];
            }
            $row['estimate_price'] = sprintf("%.2f", $realestimate_price);
            $row['estimate_weight'] = sprintf("%.2f", $realestimate_weight);
//            print_r($realgoodsList);die;
            $realgoodsList[] = [
                "recovery_category_name" => '',
                "recovery_category_id" => $data['id'],
                "weight" => $row['estimate_weight'],
                'price' =>  '客户合计',
                'unit' =>  '',
                'total_price' => $row['estimate_price']
            ];

            $row['goodsList'] = $realgoodsList;
        }
        $row['ordertime'] += 3600;
        $row['goodsList'] = json_encode($row['goodsList']);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /*查看评论*/
    public function evaluateView($ids = null)
    {
        $this->relationSearch = true;
        $row = $this->model->with(['user','rider'])->find($ids)->toArray();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ( $row['evaluatetime'] == 0) {
            $this->error(__('订单未评分'));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /*订单指派*/
    public function designate($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                /*重置订单状态*/
                $params['status'] = 0;//订单修改待接单
                $params['admin_designate'] = 1;//系统指派标识为 是
                $result = false;
                Db::startTrans();
                try {
                    /*写入订单日志*/
                    $modelRecoveryOrderStatus = new RecoveryOrderStatus();
                    $modelRecoveryOrderStatus->allowField(true)->save([
                        'recovery_order_id' => $row->id,
                        'change_type' => 'admin_designate',//类型为系统指派
                        'change_message' => '系统指派订单',
                        'createtime' => time()
                    ]);
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 检测是否有新订单消息
     */
    public function isHaveNewAfter(){
        $tipsNumber = $this->model->where('status',0)->count();
//        $tips = 'newOrder:tips:number';
//        $tipsNumber = Cache::get($tips) ?: 0;
        $this->success('获取新订单消息数量成功', null, $tipsNumber);
    }
    /**
     * 已确认新订单消息
     */
     public function handleTui()
     {
         $type = $this->request->post('type');
         $tips = 'newOrder:tips:number';
         Cache::set($tips, 0);
         $this->success('确认新订单消息成功', null, $type);
     }
}
